/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { Cell, CellProps } from '../../doc/cell';
import { DatePicker } from '@knno/ui/datePicker';
import time from '@knno/time';

function editTime(
	cell: Cell,
	attrs: CellProps,
	mode: 'dy' | 'dm' | 'dd',
	getValue: (str: string) => Date,
	setValue: (date: Date) => string
) {
	function openSelect() {
		DatePicker.show({
			refer: cell,
			date: [getValue(cell.getValue())],
			range: false,
			focus: true,
			mode,
		}).onSelect((value) => {
			cell.setValue(setValue(value as Date));
			cell.text(cell.getValue() + '');
		});
	}
	cell.text(cell.getValue() ?? '');
	cell.addClass('select');
	cell.on('click', () => {
		if (!attrs.readonly) {
			openSelect();
		}
	});
	cell.on('keydown', (evt) => {
		if (evt.key === ' ') {
			evt.preventDefault();
			evt.stopPropagation();
		}
	});
	cell.on('keyup', (evt) => {
		if (evt.key === ' ' || evt.key === 'Space' || evt.key === 'Enter') {
			evt.preventDefault();
			evt.stopPropagation();
			if (!attrs.readonly) {
				openSelect();
			}
		}
	});
}

export function year(cell: Cell, attrs: CellProps) {
	editTime(
		cell,
		attrs,
		'dy',
		(str) =>
			new Date(
				str === '' || (typeof str !== 'string' && typeof str !== 'number')
					? new Date().getFullYear() + 1
					: parseInt(str),
				0,
				1
			),
		(date) => date.getFullYear() + ''
	);
}

export function month(cell: Cell, attrs: CellProps) {
	editTime(
		cell,
		attrs,
		'dm',
		(str) => (str === '' || typeof str !== 'string' ? new Date() : time.parse(str, 'yyyy-MM')!),
		(date) => time.format(date, 'yyyy-MM')!
	);
}

export function date(cell: Cell, attrs: CellProps) {
	editTime(
		cell,
		attrs,
		'dd',
		(str) => (str === '' || typeof str !== 'string' ? new Date() : time.parse(str, 'yyyy-MM-dd')!),
		(date) => time.format(date, 'yyyy-MM-dd')!
	);
}
